package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.entity.Warning;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.service.IWarningService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-05-27
 */
@Slf4j
@Api(value = "", tags = "", description = "")
@RestController
@RequestMapping("/health/warning")
public class WarningController {
    @Autowired
    private IWarningService warningService;

    @Autowired
    private IUserService userService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新", notes = "新增或更新")
    public Result save(@RequestBody Warning warning){
        return Result.success(warningService.save(warning));
    }

    // 根据ID删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public Result delete(@PathVariable Integer id){
        return Result.success(warningService.removeById(id));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(warningService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部", notes = "查询全部")
    public Result findAll(){
        return Result.success(warningService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
    public Result findOne(@PathVariable Integer id){
        return Result.success(warningService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") Integer uid,
                           @RequestParam(required = false, defaultValue = "") String flag){
        if (uid == null){
            return Result.error(Constants.CODE_500, "参数为空");
        }
        QueryWrapper<Warning> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid);
        if (StringUtils.isNotBlank(flag)){
            wrapper.eq("patientFlag", flag);
        }
        wrapper.orderByDesc("createtime");
        return Result.success(warningService.page(new Page<>(pageNum,pageSize), wrapper));
    }

    @ApiOperation(value = "根据医生id 查询自己的病人是否存在异常数据", notes = "根据医生id 查询自己的病人是否存在异常数据")
    @PostMapping("/findWarning")
    public Result findWarning(@RequestBody Map params){
        Set<String> patientNames = null;
        try {
            log.info("findWarning method start..................");
            // 查询医生所在医院所有的病人信息
            QueryWrapper<SysUserEntity> userWrapper = new QueryWrapper<>();
            userWrapper.eq(StringUtils.isNotBlank(String.valueOf(params.get("hid"))),"hid", params.get("hid"));
            userWrapper.eq("type", 0);
            List<SysUserEntity> users = userService.list(userWrapper);
            if (users.size() == 0){
                return Result.error(Constants.CODE_500,"未找到所属用户!");
            }
            // 根据病人id 查询是否存在截止到目前的未处理异常信息
            List<Warning> warnings = null;
            for (SysUserEntity user : users) {
                QueryWrapper<Warning> warningWrapper = new QueryWrapper<>();
                warningWrapper.eq("uid", user.getUserId());
                warningWrapper.le("createtime", params.get("date"));
                warningWrapper.eq("doctorFlag", 0);
                warnings = warningService.list(warningWrapper);
            }
            patientNames = new HashSet<>();
            for (Warning warning : warnings) {
                SysUserEntity user = userService.getRedisByUid(warning.getUid());
                patientNames.add(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(patientNames);
    }

    @ApiOperation(value = "医生确认异常信息", notes = "医生确认异常信息")
    @GetMapping(value = "/confirmWarning/{id}")
    public Result confirmWarning(@PathVariable String id){
        log.info("confirmWarning method start............");
        LambdaUpdateWrapper<Warning> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Warning::getDoctorFlag, 1);
        wrapper.eq(StringUtils.isNotBlank(id), Warning::getId, id);
        boolean update = warningService.update(wrapper);
        log.info("response value is {}", update);
        if (update){
            return Result.success("ok");
        } else {
            return Result.error(Constants.CODE_500, "消息确认出错,请联系管理员!!");
        }
    }

    @ApiOperation(value = "患者确认异常信息", notes = "患者确认异常信息")
    @GetMapping(value = "/confirmWarningByUser/{id}")
    public Result confirmWarningByUser(@PathVariable String id){
        log.info("confirmWarningByUser method start............");
        LambdaUpdateWrapper<Warning> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Warning::getPatientFlag, 1);
        updateWrapper.eq(StringUtils.isNotBlank(id), Warning::getId, id);
        boolean update = warningService.update(updateWrapper);
        log.info("response value is {}", update);
        if (update){
            return Result.success("ok");
        } else {
            return Result.error(Constants.CODE_500, "消息确认出错,请联系管理员!!");
        }
    }


}

